#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :fn_three_price.py
# @Time      :2024/11/11 22:20
# @Author    :zhou_yi
import asyncio
from tools.units import DATETIME, CHART, FILE, Path
from models.ThreePrice import InputThreePrice, PriceCompany, OutThreePrice  # 验证模型
from service.fn_db import companyDB
from settings import FmtLst, Root  # 基本设置


# 生成数据
async def three_price_context(In: InputThreePrice) -> OutThreePrice:
    start = In.start
    end = In.end

    service_date = f"{start.year}年{start.month}月{start.day}日至{end.year}年{end.month}月{end.day}日"
    months = DATETIME.month_diff(start, end)  # 月差

    three = []
    for name, signal_price in zip(In.companies, In.prices):
        sign_date: str = DATETIME.random_date_format(DATETIME.random_date_front(start, 10), FmtLst)
        price = signal_price * In.nums * months
        c = await companyDB.fetch_by_name(name=name)
        c.update({
            'service_date': service_date,
            'months': f"{months}",
            'nums': f"{In.nums}",
            'signal_price': f"{signal_price:.2f}",
            'price': f"{price:.2f}",
            'up_price': CHART.rmb_upper(price),
            'sign_date': sign_date
        })
        three.append(PriceCompany(**c))

    json_: dict = {
        'partA': In.partA,
        'service_date': service_date,
        'three': three,
    }

    context = OutThreePrice(**json_)

    return context


# 生成文件
async def file_three_price(In: InputThreePrice) -> tuple:
    """
        生成三方比价文件
    :param In:
    :return: path,filename
    """
    filename = Path(Root) / f"tmp/{CHART.uid_key()}.docx"
    context = await three_price_context(In)
    res = FILE.word_file(In.tpl, context.dict(), filename.__str__())
    download_name = f"三方比价_垃圾清运_{In.partA}.docx"
    return res, download_name


# 生成ByteIO对象
async def io_three_price(In: InputThreePrice) -> tuple:
    """
        生成三方比价文件
    :param In:
    :return: io,download_name
    """
    context = await three_price_context(In)
    io_ = FILE.word_Io(In.tpl, context.dict())
    download_name = f"三方比价_垃圾清运_{In.partA}.docx"
    return io_, download_name


if __name__ == '__main__':
    _dic = {
        'tpl': "E:/py_code/prj_6/tpl/模版_三方比价_有害垃圾清运.docx",
        'partA': '北京市顺义区马坡第一幼儿园',
        'start': '2024-11-01',
        'end': '2025-07-31',
        'companies': [
            "北京宏鑫汇能循环经济发展科技有限公司",
            "北京智分瓦力环境工程有限公司",
            "北京铨胜恒德再生资源有限公司"
        ],
    }

    r = asyncio.run(file_three_price(InputThreePrice(**_dic)))

    print(r)

    ...
